﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAPI_Demo.Filter
{
    public class CustomerResourceFilterAttribute : Attribute, IResourceFilter
    {
        /// <summary>
        /// 通过资源过滤器 实现资源缓存
        /// 
        /// 当第一次请求接口的时候 记录下请求下来的结果（数据）
        /// 当下一次请求 去判断有没有已经被缓存下来的数据
        /// 不同接口 数据不一样 以接口地址 为数据保持key
        /// </summary>
        private static Dictionary<string, object> cacheDic = new Dictionary<string, object>();
        /// <summary>
        /// 请求资源前
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
            //使用请求路径 去获取保持下来的数据
            var path = context.HttpContext.Request.Path;
            if (cacheDic.ContainsKey(path))
            {
                //把缓存下来的数据 赋值给请求结果
                context.Result = (IActionResult)cacheDic[path];
            }
            Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecuting");
        }
        /// <summary>
        /// 请求之后
        /// </summary>
        /// <param name="context"></param>
        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            //把资源
            var path = context.HttpContext.Request.Path;
            cacheDic[path] = context.Result;
            Console.WriteLine("CustomerResourceFilterAttribute.OnResourceExecuted");
        }
    }
}
